<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

/**
 * 采购明细
 *
 * @icon fa fa-circle-o
 */
class Produce extends Backend
{
	/**
     * 是否是关联查询
     */
    protected $relationSearch = TRUE;
    /**
     * Bill模型对象
     * @var \app\admin\model\Bill
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Bill;
        $this->modelCut = new \app\admin\model\Cut;
        $this->modelCutbill = new \app\admin\model\Cutbill;        
    }


    public function index()
    {
    	//设置过滤方法
    	$this->request->filter(['strip_tags', 'trim']);
    	if (false === $this->request->isAjax()) {
    		return $this->view->fetch();
    	}
    	//如果发送的来源是 Selectpage，则转发到 Selectpage
    	if ($this->request->request('keyField')) {
    		return $this->selectpage();
    	}
    	[$where, $sort, $order, $offset, $limit] = $this->buildparams();
    	$list = $this->model
			    	 ->where($where)
			    	 ->order($sort, $order)
			    	 ->paginate($limit);
    	$result = ['total' => $list->total(), 'rows' => $list->items()];
    	return json($result);
    }
    
    
    /**
	 * @生产 确定裁床录入
     */
    public function add($ids = null)
    {
    	$ids = $ids ?: $this->request->post('ids');
    	if (false === $this->request->isPost()) {
    		$billList = $this->model->with('purchase')->where('bill.id', 'in', $ids)->select();
    		$purchaseCerts = $this->model->with('purchase')->where('bill.id', 'in', $ids)->group('purchase_id')->column('image');
    		$this->assign("purchase", $billList[0]['purchase']);    		
    		$this->assign("jsonBill", json_encode($billList));
    		$this->assign('produceSn', 'P'.date('YmdHis'));
    		$this->assign('purchase_certs', implode(',', $purchaseCerts));
    		return $this->view->fetch();
    	}
    	$params = $this->request->post('row/a');
    	if (empty($params)) {
    		$this->error(__('Parameter %s can not be empty', ''));
    	}
    	$params = $this->preExcludeFields($params);
    
    	if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
    		$params[$this->dataLimitField] = $this->auth->id;
    	}
    	$result = false;
    
    	Db::startTrans();
    	try {
    		//是否采用模型验证
    		if ($this->modelValidate) {
    			$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
    			$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
    			$this->model->validateFailException()->validate($validate);
    		}
    		
    		$params['editer_id'] = $this->auth->id;
    		$result = $this->modelCut->allowField(true)->save($params);
    		

    		//裁床明细
    		$cutId 	 = $this->modelCut->id;
    		$cutBills = json_decode($params['bill'], 1);    		
    		foreach ($cutBills as $k=>$v){
    			$cutBills[$k]['cut_id'] = $cutId;
    			db('bill')->where('id', $v['bill_id'])->setField('is_plan', 1);
    		}
    		$result = $this->modelCutbill->allowField(true)->saveAll($cutBills);

    		//裁床订单明细
    		$billCut = '';
    		
    		Db::commit();
    	} catch (ValidateException|PDOException|Exception $e) {
    		Db::rollback();
    		$this->error($e->getMessage());
    	}
    	if ($result === false) {
    		$this->error(__('No rows were inserted'));
    	}
    	$this->success();
    }


}
